package com.killer.view;


import com.killer.io.HttpOutputStream;
import com.killer.servlet.ServletResponse;
import com.killer.util.HttpProtocolUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

public class Response implements ServletResponse{

    private OutputStream outputStream;

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }



    public void response(String data) throws IOException {
        outputStream.write(data.getBytes());
    }

    public void outputStatisticResource(File resourceFile) throws IOException {
        if (!resourceFile.exists()) {
            response(HttpProtocolUtil.getRep404Header());
        }
        //读取文件，然后输出
        FileInputStream inputStream = new FileInputStream(resourceFile);
        long total=inputStream.available();
        //先输出响应头
        response(HttpProtocolUtil.getRep200Header(inputStream.available()));
        int bufferSize=2048;
        byte[] buffer=new byte[bufferSize];
        int totalRead=0;
        while (totalRead < total) {
            //剩余未读
            long remainRead=total-totalRead;
            if (remainRead < bufferSize) {
                bufferSize=(int)remainRead;
                buffer=new byte[bufferSize];
                inputStream.read(buffer);
            }else{
                inputStream.read(buffer);
            }
            //输出
            outputStream.write(buffer);
            totalRead=totalRead+bufferSize;
        }
        outputStream.flush();
    }

    @Override
    public OutputStream getOutputStream() {
        return outputStream == null ? null : new HttpOutputStream(outputStream);
    }
}
